package pdd;

import java.lang.reflect.*;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by gtx on 2018/6/11.
 * 拼多多request接口
 * 实现类中不允许出现Date、数组、集合类型
 * @author gtx
 */
public abstract class PddRequest<T extends PddResponse> {

    public static final String JSON_RESPONSE = "JSON";
    public static final String XML_RESPONSE = "XML";

    public static final String DEFAULT_API_VERSION = "V1";

    /**
     * 获取系统级请求参数
     * @return 系统级请求参数
     */
    public Map<String, String> getSysParams() {
        Map<String,String> params = new HashMap<>();
        params.put("type",this.getType() == null ? null : this.getType());
        params.put("timestamp",String.valueOf(System.currentTimeMillis()));
        params.put("data_type",this.getDataType() == null ? null : this.getDataType());
        params.put("version",this.getVersion() == null ? null : this.getVersion());
        return params;
    }
    /**
     * 获取请求参数
     * @return  请求参数
     */
    public Map<String, String> getParams(){
        Map<String, String> params = getSysParams();

        Class<? extends PddRequest> clazz = this.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields){
            field.setAccessible(true);
            String fieldName = field.getName();
            Method method = null;
            try {
                String fieldType = field.getGenericType().toString();
                StringBuffer stringBuffer = new StringBuffer();
                if (fieldType.equals(boolean.class.getName())) {
                    method = clazz.getMethod(stringBuffer.append("is").append(fieldName.substring(0,1).toUpperCase()).append(fieldName.substring(1,fieldName.length())).toString());
                }else {
                    method = clazz.getMethod(stringBuffer.append("get").append(fieldName.substring(0,1).toUpperCase()).append(fieldName.substring(1,fieldName.length())).toString());
                }
                Object obj = method.invoke(this);
                if (obj == null) {
                    continue;
                }
                params.put(fieldName,String.valueOf(obj));
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }

        return params;
    }

    /**
     * 获取响应格式，即返回数据的格式，XML或者JSON（二选一），默认JSON，注意是大写。
     * @return 响应格式
     */
    public String getDataType() {
        return JSON_RESPONSE;
    }

    /**
     * 获取API接口名称。
     * @return API接口名称
     */
    public String getType(){
        return this.getClass().getPackage().getName();
    }

    /**
     * API协议版本号。默认为V1
     * @return API版本号
     */
    public String getVersion() {
        return DEFAULT_API_VERSION;
    }

    /**
     * 获取request对应的response的class
     * @return responses.class
     */
    public Class<T> getResponseClass() {
        return (Class<T>)((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }
    //    public Class<T> getResponseClass() throws ClassNotFoundException {
//        Class<? extends PddRequest> reqClass = this.getClass();
//        String clazzStr = reqClass.getName();
//        int index = clazzStr.lastIndexOf(".");
//        StringBuffer stringBuffer = new StringBuffer();
//        String resClassStr = stringBuffer.append(clazzStr.substring(0, index))
//                .append(clazzStr.substring(index, clazzStr.length())
//                        .replace("Request", "Response")).toString();
//        return (Class<T>) Class.forName(resClassStr);
//    }


}
